package cn.zwxky.android.staff.HomePage;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.format.Time;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.net.Token;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.Camera.LsfbCamera;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.zwxky.android.staff.Login.ForgetBean;
import cn.zwxky.android.staff.R;
import cn.zwxky.android.staff.Utils.LittleUtils;
import cn.zwxky.android.staff.Utils.MyCamera;
import cn.zwxky.android.staff.Utils.NoDoubleClickUtils;
import cn.zwxky.android.staff.Utils.Permission;
import cn.zwxky.android.staff.Utils.URLString;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 签到页面
 * Created by Administrator on 2017/3/29 0029.
 */
@ContentView(R.layout.aty_sign)
public class SignActivity extends LsfbActivity {

    @ViewInject(R.id.aty_sign_img_photo)
    private SimpleDraweeView img_photo;

    @ViewInject(R.id.aty_sign_img_photo2)
    private SimpleDraweeView img_photo2;

    /**
     * 备注
     */
    @ViewInject(R.id.aty_sign_et_impirt)
    private EditText et_impirt;

    /**
     * 时间
     */
    @ViewInject(R.id.aty_sign_text_time)
    private TextView text_time;

    /**
     * 地址
     */
    @ViewInject(R.id.aty_sign_text_address)
    private TextView text_address;

    /**
     * 封装好的照相机
     */
    private MyCamera camera;

    /**
     * 头像存储
     */
    private String mimage = "";

    private Uri uri;

    private Handler handler=new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what){
                case 1000:
                    img_photo2.setVisibility(View.VISIBLE);
                    img_photo2.setImageURI(Uri.parse(URLString.IMG_URL+mimage));
                    break;
            }
        }
    };

    @Override
    public void initView() {
        LittleUtils.setsimpletitlebar(this, "签到");
        TextView textView = new TextView(this);
        textView.setText("提交");
        textView.setTextColor(getResources().getColor(R.color.white_color));
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.hideSoftInputFromWindow(et_impirt.getWindowToken(), 0);
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    sign();
                }

            }
        });
        getTitleBar().setRightView(textView, 0, 0, DensityUtils.dp2px(this, 10), 0);

        Permission permission = new Permission(SignActivity.this);
        permission.GetCAMEARPermission();

        if (LittleUtils.address==null){
            SN.SnackShow(et_impirt,"定位信息获取失败");
        }
        text_address.setText(LittleUtils.address);

        Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month+1;
        int date = t.monthDay;
        int hour = t.hour; // 0-23
        int minute = t.minute;
        text_time.setText(year+"年"+month+"月"+date+"日  "+hour+":"+minute);

        camera = new MyCamera() {
            @Override
            public void resultUri(Uri uri) {
                SignActivity.this.uri = uri;
            }
        };
    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_sign_img_photo})
    public void onClick(View view) {
        switch (view.getId()) {
            //照相机
            case R.id.aty_sign_img_photo:
                camera.show(SignActivity.this, SignActivity.this);
//                camera.gotoCamera();
                break;
        }
    }

    @Override
    public void initData() {

    }

    public void sign() {

        if (et_impirt.getText().toString().isEmpty()) {
            SN.SnackShow(et_impirt, "请输入备注信息");
            return;
        }

        if (mimage.isEmpty()){
            SN.SnackShow(et_impirt, "请在当前地点拍照");
            return;
        }

        if (LittleUtils.address==null){
            SN.SnackShow(et_impirt,"定位信息获取失败，请重新获取");
        }

        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid", Config.getUserId());
        hashMap.put("addr", LittleUtils.address);
        hashMap.put("con", et_impirt.getText().toString());
        hashMap.put("img", mimage);
        new BaseInternet().getData(URLString.SIGN, hashMap, ForgetBean.class, new SignEvent<ForgetBean>(), false);
    }

    @EventAnnotation
    public void SignEvent(SignEvent<ForgetBean> event) {
        switch (event.getCode()) {
            case 200:
                T.showShort(this,event.getMsg());
                finish();
                break;
            default:
                SN.SnackShow(et_impirt,event.getMsg());
                break;
        }
    }

    private static final int REQUEST_CODE_WRITE_SETTINGS = 2;
    private boolean isXiangce=true;

    /**
     * 头像选择回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);

        LsfbLog.e("requestCode" + requestCode);
        LsfbLog.e("resultCode" + resultCode);

        if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Settings.System.canWrite(this)) {
                LsfbLog.e("onActivityResult write settings granted");
            } else {
                LsfbLog.e("请求失败");
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LsfbCamera.REQUESTCODE:
                    LsfbLog.e(uri.toString());
                    isXiangce=false;
                    camera.crop(uri, 300);
                    break;
                case LsfbCamera.SYSTEMPHOTOS:
                    LsfbLog.e(data.getData().toString());
                    String url = "file://" + LsfbCamera.getPath(this, data.getData());
                    LsfbLog.e("22222222222222" + url);
                    uri = Uri.parse(url);
                    isXiangce=true;
                    camera.crop(uri, 300);
//                    File zipfile= ZipPic.zippng(uri.getPath());
//                    camera.crop(Uri.parse("file://"+zipfile.getPath()), 300);
                    break;
                case LsfbCamera.CROPIMG:
                    List<File> list = new ArrayList<>();
                    LsfbLog.e("---------------------------------------------:" + uri.getPath());
                    if (isXiangce){
                        try {
                            String url1 = "file://" + LsfbCamera.getPath(this, data.getData());
                            list.add(new File(Uri.parse(url1).getPath()));
                        }catch(Exception e){
                            list.add(new File(uri.getPath()));
                        }
                    }else {
                        list.add(new File(uri.getPath()));
                    }

//                    LsfbServerUpload.server(this, list, new IServerCall<String[]>() {
//                        @Override
//                        public void call(String[] strings) {
//                            LsfbLog.e("fsdfds");
//                            mimage = strings[0];
//                            post();
//                            LsfbLog.e("3333333333" + uri.getPath());
//                        }
//                    });
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("uid",Config.getUserId());
                    hashMap.put("img",list.get(0).getPath());
                    // TODO: 2017/3/28 0028 头像上传~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    new HttpClient().postFile(URLString.IMGUPLOAD + Token.getToken(URLString.IMGUPLOAD), hashMap, list, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            LsfbLog.e(e.getLocalizedMessage());
                            LsfbLog.e("上传失败");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            LsfbLog.e("上传success");
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().string());
//                                LsfbLog.e("上传结果" + response.body().string());
                                LsfbLog.e("上传结果" + jsonObject.toString());
                                if (jsonObject.getInt("code") == 200) {
                                    LsfbLog.e("得到回调");
                                    JSONObject img = jsonObject.getJSONObject("data");
                                    mimage = img.getString("img");
                                    handler.sendEmptyMessage(1000);
                                } else {
                                    LsfbLog.e("得到失败回调");
                                    T.showShort(SignActivity.this, jsonObject.getString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    break;
            }
        }
    }

}
